export const locationService = {
    getUserPosition: () => {
        return new Promise((resolve, reject) => {
            var map, geolocation;
            //加载地图，调用浏览器定位服务
            map = new AMap.Map('container', {
                resizeEnable: true
            });
            const options = {
                enableHighAccuracy: true, //是否使用高精度定位，默认:true
                timeout: 10000, //超过10秒后停止定位，默认：无穷大
                maximumAge: 0, //定位结果缓存0毫秒，默认：0
                convert: true, //自动偏移坐标，偏移后的坐标为高德坐标，默认：true
                showButton: true, //显示定位按钮，默认：true
                buttonPosition: 'LB', //定位按钮停靠位置，默认：'LB'，左下角
                buttonOffset: new AMap.Pixel(10, 20), //定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
                showMarker: true, //定位成功后在定位到的位置显示点标记，默认：true
                showCircle: true, //定位成功后用圆圈表示定位精度范围，默认：true
                panToLocation: true, //定位成功后将定位到的位置作为地图中心点，默认：true
                zoomToAccuracy: true //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
            }

            AMap.plugin(['AMap.Geolocation'], () => {
                const geolocation = new AMap.Geolocation(options);
                // ios环境切换到使用远程https定位
                if (AMap.UA.ios && document.location.protocol !== 'https:') {

                    //使用远程定位，见 remogeo.js
                    var remoGeo = new RemoGeoLocation();

                    //替换方法
                    navigator.geolocation.getCurrentPosition = function () {
                        return remoGeo.getCurrentPosition.apply(remoGeo, arguments);
                    };

                    //替换方法
                    navigator.geolocation.watchPosition = function () {
                        return remoGeo.watchPosition.apply(remoGeo, arguments);
                    };
                }
                map.addControl(geolocation);
                geolocation.getCurrentPosition();
                AMap.event.addListener(geolocation, 'complete', (result) => {
                    console.log('Geolocation complete:', result);
                    locationService.onComplete(result, resolve, reject);
                });
                AMap.event.addListener(geolocation, 'error', (err) => {
                    console.error('Geolocation error:', err);
                    locationService.onError(err, resolve, reject);
                });
            });
        });
    },
    onComplete: (result, resolve, reject) => {
        const { lng, lat } = result.position;
        window.latitude = result.position.getLat()
        window.longitude = result.position.getLng()
        const address = `${result.position.getLat()}, ${result.position.getLng()}`; // 提供默认地址
        resolve({
            lat,
            lng,
            address
        });
    },
    onError: (err, resolve, reject) => {
        let errorMessage = '定位失败，请确保已开启定位服务并授权访问位置信息';
        switch (err.info) {
            case 'NOT_SUPPORTED':
                errorMessage = '该设备不支持定位功能';
                break;
            case 'TIMEOUT':
                errorMessage = '定位超时，请重试';
                break;
            case 'POSITION_UNAVAILABLE':
                errorMessage = '无法获取当前位置';
                break;
            default:
                errorMessage = `定位错误：${err.message}`;
        }
        reject(new Error(errorMessage));
    }
};